package com.humble.vichatbackend.interceptor;

import com.humble.vichatbackend.constant.UserConstant;
import com.humble.vichatbackend.exception.BusinessException;
import com.humble.vichatbackend.model.enums.ErrorCode;
import com.humble.vichatbackend.model.vo.UserVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import java.util.Map;

@Slf4j
public class WebSocketInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserVO currentUser = (UserVO)request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        Map<String, String> pathVariables =
                (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        if(pathVariables != null&&pathVariables.containsKey("id")&&pathVariables.containsKey("teamId")) {
            long id = Long.parseLong(pathVariables.get("id"));
            return currentUser.getId().equals(id);
        }
        log.error("发送消息时携带ID与当前用户ID不同或未携带用户ID",40000);
        return false;
    }
}
